// 运行时配置
import { message } from 'antd';
import adminAPI from './services/admin';

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState() {
  // 路由权限控制
  if (location.pathname === '/login') {
    // 如果用户已经登录，则强制跳转至首页
    const token = localStorage.getItem('adminToken');
    if (token) {
      // 先是校验token是否有效
      const resp = await adminAPI.getInfo();
      if (resp.data) {
        // 那么就不允许跳转
        message.warning('请先退出后再登录');
        history.go(-1);
      }
    }
  } else {
    // 要跳转至非登录页，此操作需要登录后才有权限访问
    const resp = await adminAPI.getInfo();
    if (resp.data) {
      // 已登录，需要换区登录账号相关信息
      const { data } = await adminAPI.getAdminById(resp.data._id);
      return {
        name: data.nickname,
        avatar: data.avatar,
        adminInfo: data,
      };
    } else {
      // token失效或未登录
      // 1. 删除token
      localStorage.removeItem('adminToken');
      // 2. 跳转至登录页
      location.href = '/login';
      message.warning('登录过期，请重新登录');
    }
  }
}

export const layout = () => {
  return {
    logo: 'https://xiejie-typora.oss-cn-chengdu.aliyuncs.com/2022-10-18-074620.png',
    menu: {
      locale: false,
    },
    logout: () => {
      localStorage.removeItem('adminToken');
      location.href = '/login';
      message.success('退出登录成功');
    },
  };
};
const authHeaderInterceptor = (url, options) => {
  const token = localStorage.getItem('adminToken');
  let _options = { ...options };
  if (token) {
    _options.headers['Authorization'] = `Bearer ${token}`;
  }
  return {
    url: `${url}`,
    options: _options,
  };
};
export const request = {
  // 新增自动添加AccessToken的请求前拦截器
  requestInterceptors: [authHeaderInterceptor],
};
